﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Linkbase;
using System.Text.RegularExpressions;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Utilities;
using Saxon.Api;
using System.Xml.Linq;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The location filter can be used to select facts that have a specified
    /// location relative to the location of another fact. 
    /// </summary>
    public class LocationFilter : Filter
    {
        private string variable;

        /// <returns> The @variable attribute on the sibling filter. </returns>
         public string Variable
        {
            get { return variable; }
            set { variable = value; }
        }

        private string location;

        /// <returns> The @location attribute on the location filter. </returns>
        public string Location
        {
            get { return location; }
            set { location = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public LocationFilter(Resource resource)
            : base(resource)
        {
            string qname = (string)resource.ResourceXElement.Attribute("variable") ?? string.Empty;
            qname = qname.TrimEnd().TrimStart();
            qname = Regex.Replace(qname, @"\s+", " ");
            variable = qname;

            string expression = (string)resource.ResourceXElement.Attribute("location") ?? string.Empty;
            expression = expression.TrimEnd().TrimStart();
            expression = Regex.Replace(expression, @"\s+", " ");
            location = expression;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem item in itemsToFilter)
            {
                FactVariable factVariable = GetFactVariable(Variable, variableSet);

                List<FactItem> inputFacts = GetItems(dts.Instance.Facts);

                List<FactItem> factItems = variableSet.FilteringFacts(variableSet, factVariable, inputFacts);

                string location = EvaluateXPathExpression(variableSet, Location, factItems[0].FactElement.ToXmlNode());

                XElement locationX = XElement.Parse(location);

                if (factItems.Count > 0)
                {
                    if (Complement ? !factItems[0].FactElement.Parent.Equals(location) : XNode.DeepEquals(item.FactElement.Parent, locationX))
                    {
                        itemListTemp.Add(item);
                        continue;
                    }
                }

            }

            return itemListTemp;
        }
    }
}
